<?php

namespace app\shop\controller\plus;

use app\shop\controller\Controller;
use app\common\model\plus\point\PointProduct as PointProductModel;

/**
 * Class Officia
 * 商品推荐控制器
 * @package app\shop\controller\plus\officia
 */
class PointProduct extends Controller
{
    //等级商品表
    public function index()
    {
        $res = PointProductModel::with([
            'product' => function ($query) {
                $query->with(['image.file']);
            }
        ])->select();
        $lists = [];
        foreach ($res as $item) {
            $lists[] = [
                'product_id' => $item['product_id'],
                'product_name' => $item['product']['product_name'],
                'product_image' => $item['product']['image'][0]['file_path'] ?? "",
                'point_price' => $item['point_price'],
                'quota' => $item['quota'],
            ];
        }
        return $this->renderSuccess('', $lists);
    }

    public function save()
    {
        $data = $this->postData();
        $app_id = $this->store['app']['app_id'];
        $exist_ids = PointProductModel::column('product_id');
        $products = $data['products'] ?? [];
        $post_ids = [];
        foreach ($products as $v) {
            $product_id = $v['product_id'] ?? 0;
            if (!$product_id) {
                continue;
            }
            $post_ids[] = $product_id;
            $model = PointProductModel::where(['product_id' => $product_id, 'app_id' => $app_id])->find();
            if ($model) {
                $model->save($v);
            } else {
                PointProductModel::create([
                    'product_id' => $product_id,
                    'app_id' => $app_id,
                    'point_price' => $v['point_price'],
                    'quota' => $v['quota'],
                ]);
            }
        }
        //删除在exist_ids中，不在post_ids中的删除
        $del_ids = array_diff($exist_ids, $post_ids);
        if ($del_ids) {
            PointProductModel::destroy(function ($query) use ($del_ids) {
                $query->whereIn('product_id', $del_ids);
            });
        }
        return $this->renderSuccess('保存成功');
    }
}